package com.powernode.ssm.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil; 
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; 
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.ssm.dao.*;
import com.powernode.ssm.pojo.vo.*;
import com.powernode.ssm.pojo.po.*;
import com.powernode.ssm.pojo.bo.*;
import com.powernode.ssm.service.*;
import com.powernode.ssm.utils.*;
import com.powernode.ssm.utils.pdf.TestPdfGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

@Slf4j
@Service
public class TestPdfServiceImpl extends ServiceImpl<TestPdfDao, TestPdfPo> implements TestPdfService {

   @Autowired
   TestPdfDao testPdfDao;

   @Autowired
   TestPdfGenerator testPdfGenerator;

   @Autowired
   private SpringUtils springUtils;

   @Value("${export.template_path}")
   private String tempPath;
   @Value("${export.exportPath}")
   private String exportPath; 

   @Value("${export.dsp}")
   private boolean encrypt;

   @Override
   public ResponseUtils queryTestPdf (QueryTestPdfVo queryTestPdfVo) {

       int current = queryTestPdfVo.getCurrentPage();
       int size = queryTestPdfVo.getPageSize();

        Page<TestPdfPo> page = testPdfDao.queryTestPdf(
               new Page<>(current, size), queryTestPdfVo);

        PageBo pageBo = PageBo.builder()
               .current(current)
               .size(size)
               .total(page.getTotal())
               .dataList(page.getRecords())
               .build();

       return new ResponseUtils<>(ReturnCodeEnum.SUCCESS.getCode(),ReturnCodeEnum.SUCCESS.getMsg(),pageBo);
   }

   @Override
   public ResponseUtils exportPdf(HttpServletResponse httpServletResponse, H5UserinfoPo h5UserinfoPo, QueryTestPdfVo item) {

       int current = item.getCurrentPage();
       int size = item.getPageSize();
       String suffix = ".pdf";//后缀名

       List<TestPdfPo> data = testPdfDao.queryTestPdf(
               new Page<>(current, size), item).getRecords();

       String pdfPath = testPdfGenerator.savePdf2Path(data);

       //读取导出到指定服务器目录的pdf返回输出流给前端
       ImportAndExportUtils.export(httpServletResponse, h5UserinfoPo,encrypt,
               pdfPath.substring(0,pdfPath.lastIndexOf(".")), suffix);

       springUtils.saveLog("导出测试pdf数据");
       return null;
   }

}
